<template>
  <div :style="{height:myConfig.height + 'px', width:'100%'}"/>
</template>

<script>
import brace from 'brace'
require('brace/ext/language_tools')
var langTools = brace.acequire('ace/ext/language_tools')

const defaultConfig = {
  value: '',
  width: 500,
  height: 400,
  lang: 'mysql',
  theme: 'xcode',
  readOnly: false,
  fullScreen: false,
  autoCompletion: true,
  tabSize: 0,
  copyWithEmptySelection: true
}
export default {
  name: 'AceEditor',
  props: {
    config: {
      type: Object,
      default() {
        return {}
      }
    },
    customCompleteData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      $ace: null,
      myConfig: Object.assign({}, defaultConfig, this.config)
    }
  },
  watch: {
    config(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.myConfig = Object.assign({}, defaultConfig, newVal)
        this.initAce(this.myConfig)
      }
    },
    customCompleteData(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.addCompleter(newVal)
      }
    }
  },
  mounted() {
    if (this.myConfig) {
      this.initAce(this.myConfig)
    } else {
      this.initAce(defaultConfig)
    }
  },
  methods: {
    addCompleter: function(data) {
      langTools.addCompleter({
        getCompletions: function(editor, session, pos, prefix, callback) {
          if (prefix.length === 0) {
            return callback(null, [])
          } else {
            return callback(null, data)
          }
        }
      })
    },
    initAce(conf) {
      this.$ace = brace.edit(this.$el)
      const session = this.$ace.getSession()
      this.$emit('init', this.$ace)
      require(`brace/mode/${conf.lang}`)
      require(`brace/theme/${conf.theme}`)
      // 代码提示与自动补全
      this.$ace.setOptions({
        enableBasicAutocompletion: conf.autoCompletion,
        enableLiveAutocompletion: conf.autoCompletion,
        copyWithEmptySelection: conf.copyWithEmptySelection
      })

      session.setMode(`ace/mode/${conf.lang}`) // 配置语言
      this.$ace.setTheme(`ace/theme/${conf.theme}`) // 配置主题
      this.$ace.setValue(conf.value, 1) // 设置默认内容
      this.$ace.setReadOnly(conf.readOnly) // 设置是否为只读模式
      this.$ace.setFontSize(14)
      //session.setTabSize(conf.tabSize) // Tab大小
      //session.setUseSoftTabs(true)

      //this.$ace.setShowPrintMargin(false) // 不显示打印边距
      //session.setUseWrapMode(true) // 自动换行
      // 绑定输入事件回调
      // this.$ace.on('change', ($editor, $fn) => {
      //   var content = this.$ace.getValue()
      //   this.$emit('input', content, $editor, $fn)
      // })
      this.$ace.resize()
    }
  }

}
</script>
<style scoped>
  .ace-full-screen {
    position: fixed !important;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100% !important;
    height: 100% !important;
    z-index: 10000;
  }

</style>
